angular
		.module("controller.order", [ "services" ])
		.controller(
				"ordersCtrl",
				[
						"$scope",
						"$filter",
						"$location",
						"orderFacetGroups",
						"orderSelect",
						"modals",
						"apiService",
						"alertManager",
						function($scope, $filter, $location, orderFacetGroups,
								orderSelect, modals, apiService, alertManager) {
							$scope.data = {};
							$scope.data.facetGroups = orderFacetGroups;
							$scope.data.orderSelectList = orderSelect;
							$scope.data.select = $scope.data.orderSelectList[0];
							$scope.data.changeSelect = function(select) {
								$scope.data.select = select;
							};
							$scope.data.pagination = {totalCount: 0,
								current : 0,
								size : 10,
								maxCount: 5
							};
							$scope.data.searchResult = [];
							$scope.data.changePage = function() {
								$scope.data.searchOrders();
							}
							$scope.data.costomRange = {};
							var params = $location.search();
							if (params) {
								for ( var key in params) {
									var tokens = decodeURIComponent(params[key])
											.split(",");
									if (!tokens || tokens.length === 0)
										continue;
									var group = $scope.data.facetGroups
											.find(function(g) {
												return g.index === key;
											});
									if (group && group.filters) {
										tokens
												.forEach(function(token) {
													var filter = group.filters
															.find(function(f) {
																return f.index === token;
															});
													if (filter) {
														filter.$$select = true;
													}
												});
									}
									var item = $scope.data.orderSelectList
											.find(function(se) {
												return se.index === key;
											});
									if (item) {
										$scope.data.select = item;
										$scope.data.search = tokens.join(',');
									}
								}
							}
							$scope.data.toggleDateFilter = function(group,
									filter) {
								if (filter.index === 4) {
									modals
											.dateRangeModal(
													$scope.data.costomRange.from,
													$scope.data.costomRange.to)
											.then(
													function(date) {
														$scope.data.costomRange.from = date.from;
														$scope.data.costomRange.to = date.to;
														group.filters
																.forEach(function(
																		f) {
																	f.$$select = f.index === 4;
																});
													});
								} else {
									filter.$$select = !filter.$$select;
									group.filters.forEach(function(f) {
										if (f.index !== filter.index)
											f.$$select = false;
									});
								}
							};
							$scope.data.toggleStatus = function(group, filter) {
								group.filters.forEach(function(f) {
									if (f.index === filter.index) {
										filter.$$select = !filter.$$select;
									} else {
										f.$$select = false;
									}
								});
							};
							$scope.data.searchOrders = function() {
								var params = {};
								$scope.data.facetGroups
										.forEach(function(group) {
											if (group.index === "status") {
												group.filters
														.forEach(function(
																filter) {
															if (filter.$$select) {
																params[group.index] = params[group.index]
																		|| [];
																params[group.index]
																		.push(filter.index);
															}
														});
											} else if (group.index === "contract_status"
													|| group.index === "payment_status") {
												group.filters
														.forEach(function(
																filter) {
															if (filter.$$select) {
																params[group.index] = filter.index;
															}
														})
											} else if (group.index === "date") {
												group.filters
														.forEach(function(
																filter) {
															if (!filter.$$select)
																return;
															if (filter.index === 4) {
																if ($scope.data.costomRange.from)
																	params['since'] = $scope.data.costomRange.from;
																if ($scope.data.costomRange.to)
																	params['until'] = $scope.data.costomRange.to;
															} else {
																params['since'] = filter
																		.getRange().since;
																params['until'] = filter
																		.getRange().until;
															}
														});
											}
										});
								if ($scope.data.select.index !== '') {
									params[$scope.data.select.index] = $scope.data.search
											|| "";
								}
								params["page"] = $scope.data.pagination.current - 1;
								params["size"] = 10;
								params["sort"] = "orderTime,desc";
								var formatParams = [];
								for ( var key in params) {
									if (key === "since" || key === "until") {
										formatParams.push(key
												+ "="
												+ $filter("date")(params[key],
														"yyyy.MM.dd"));
									} else if (key === "status") {
										formatParams.push("status="
												+ params[key].join(","));
									} else {
										formatParams.push(key + "="
												+ params[key]);
									}
								}
								$location.search({});
								if (formatParams) {
									formatParams
											.forEach(function(param) {
												var tokens = param.split("=");
												if (tokens.length == 2) {
													$location
															.search(
																	tokens[0],
																	encodeURIComponent(tokens[1]));
												}
											});
								}
								var realParams = formatParams.length ? ('?' + formatParams
										.join('&'))
										: '';
								apiService
										.searchOrders(realParams)
										.then(
												function(response) {
													$scope.data.searchResults = response.content;
													$scope.data.pagination = {
														totalCount : response.totalElements,
														current : response.number + 1,
														size: 10,
														maxCount: 5
													}
												},
												function(response) {
													alertManager.addAlert(
															"danger", "無法搜索訂單");
													console.log(response);
												});
							};
							$scope.data.searchOrders();
						} ])
		.controller(
				"orderCtrl",
				[
						"$scope",
						"orderDetail",
						"apiService",
						"alertManager",
						function($scope, orderDetail, apiService, alertManager) {
							$scope.data = {};
							$scope.data.orderDetail = orderDetail;
							$scope.data.approveContract = function(state) {
								apiService
										.approveContract(
												$scope.data.orderDetail.id,
												state)
										.then(
												function(data) {
													$scope.data.orderDetail.orderContractDTO.approvalStatus = 'APPROVED';
													alertManager
															.addAlert(
																	"success",
																	"成功審批合同");
												},
												function(response) {
													console.log(response)
													alertManager.addAlert(
															"danger", "審批合同失敗");
												});
							};
							$scope.data.approvePayment = function(state) {
								apiService
										.approvePayment(
												$scope.data.orderDetail.id,
												state)
										.then(
												function() {
													$scope.data.orderDetail.orderPaymentDTO.approvalStatus = 'APPROVED';
													alertManager
															.addAlert(
																	"success",
																	"成功審批合同");
												},
												function() {
													alertManager.addAlert(
															"danger", "審批合同失敗");
												});
							};
							function getDefaultCashback() {
								apiService.getDefaultCashback().then(
										function(data) {
											$scope.data.cashbackInfo = data;
										},
										function(response) {
											console.log(response);
											alertManager.addAlert("danger",
													"無法獲取返現比例");
										})
							}
							$scope.data.getCashback = function() {
								apiService
										.getCashback(orderDetail.id)
										.then(
												function(data) {
													if (!data
															|| !data.cashbackStrategy)
														getDefaultCashback();
													else {
														$scope.data.cashbackInfo = data.cashbackStrategy;
													}
												},
												function(response) {
													console.log(response);
													alertManager.addAlert(
															"danger",
															"無法獲取返現比例");
												});
							}
							$scope.data.getCashback();
							$scope.data.saveCashback = function() {
								apiService
										.saveOrderCashback(
												orderDetail.id,
												{
													percentageForCustomer : $scope.data.cashbackInfo.percentageForCustomer,
													percentageForRecommender : $scope.data.cashbackInfo.percentageForRecommender,
													percentageForManager : $scope.data.cashbackInfo.percentageForManager
												}).then(
												function(data) {
													alertManager.addAlert(
															"success",
															"保存返現比例成功");
												},
												function(response) {
													console.log(response);
													alertManager.addAlert(
															"danger",
															"無法保存返現比例");
												});
							};
							$scope.data.gotoNextState = function(nextState) {
								apiService
										.gotoNextState(orderDetail.id,
												nextState)
										.then(
												function(data) {
													$scope.data.orderDetail.orderStatus = data;
													orderDetail.orderStatus = data;
													alertManager.addAlert(
															"success",
															"成功推薦訂單狀態");
												},
												function(response) {
													console.log(response);
													alertManager.addAlert(
															"danger",
															"無法進入下個狀態");
												})
							}
							$scope.data.cancelState = function() {
								apiService
										.cancelState(orderDetail.id)
										.then(
												function(data) {
													$scope.data.orderDetail.orderStatus = data;
													alertManager
															.addAlert(
																	"success",
																	"成功取消訂單");
												},
												function(response) {
													console.log(response);
													alertManager.addAlert(
															"danger",
															"無法改變訂單狀態");
												})
							}
						} ])